<template>
  <div class="page-container">
    <!--表格内容栏-->
    <ac-table
      ref="dataTable"
      pkName="id"
      :filters="filters"
      :filterFields="filterFields"
      :columns="columns"
      :defaultSort="defaultSort"
      @handleTableOperator="handleTableOperator"
      @handleCellOperator="handleCellOperator"
    >
    </ac-table>
    <!--新增/编辑/查看界面-->
    <div class="edit-dialog">
      <el-dialog
        :title="dialogTitle"
        width="850px"
        v-model="dialogVisible"
        :close-on-click-modal="false"
        destroy-on-close
        draggable
      >
        <el-form
          :model="formData"
          label-width="110px"
          :disabled="!dialogEdit"
          :rules="rules"
          :hide-required-asterisk="!dialogEdit"
          ref="dataForm"
          label-position="right"
        >
          <el-row>
            <el-col :span="12">
              <el-form-item label="调度类型" prop="type">
                <ac-buttons
                  v-model="formData.type"
                  options="每天,每周,每月,自定义"
                />
              </el-form-item>
            </el-col>
            <el-col :span="12" v-if="formData.type !== '自定义'">
              <el-form-item label="调度时间" prop="time">
                <el-time-picker v-model="formData.time" value-format="HH:mm:ss" placeholder="时间" />
              </el-form-item>
            </el-col>
            <el-col :span="12" v-else>
              <el-form-item label="表达式" prop="expression">
                <template #label>
                  <div>
                    <span>表达式</span>
                    <el-tooltip placement="right">
                      <template #content>
                        <p>cron表达式格式: [秒] [分] [小时] [日] [月] [周] [年]</p>
                        <p>以秒为示例：</p>
                        <p style="text-indent: 28px">单值取值示例：5 * * * * ? *</p>
                        <p style="text-indent: 28px">多值取值示例：0,5,12 * * * * ? *</p>
                        <p style="text-indent: 28px">连续取值示例：0-12 * * * * ? *</p>
                        <p style="text-indent: 28px">每隔五秒示例：0/5 * * * * ? *</p>
                        <p>取值范围：秒(0~59)，分(0~59)，小时(0~23)，日(1~31)，月(0~11，0为1月)，周(1~7，1为星期日)，年(1970~2099)</p>
                        <p>示例：0 0/10 9-10 * * ?</p>
                        <p style="text-indent: 28px">每天上午9点到11点之间每10分钟触发一次</p>
                        <p>* 匹配所有可能的值</p>
                        <p>- 指定范围</p>
                        <p>/ 指定间隔值</p>
                        <p>? 不指定值，只能用在日周中</p>
                        <p>, 指定枚举值</p>
                        <p>L 表示最后，只能用在日和周中</p>
                        <p>W 工作日，只能用在日中</p>
                        <p>LW 月中最后一个工作日，只能用在日中</p>
                        <p># 月中第几个星期几：3#4 表示月的第三个星期四，只能用在周中</p>
                      </template>
                      <ac-icon iconId="018dca8ec9890493be26" style="margin-left: 5px"/>
                    </el-tooltip>
                  </div>
                </template>
                <el-input v-model="formData.expression" auto-complete="off"></el-input>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row v-if="formData.type === '每周'">
            <el-col :span="24">
              <el-form-item label="调度周期" prop="period">
                <ac-checkbox
                  v-model="formData.period"
                  options="星期一,星期二,星期三,星期四,星期五,星期六,星期天"
                />
              </el-form-item>
            </el-col>
          </el-row>
          <el-row v-if="formData.type === '每月'">
            <el-col :span="24">
              <el-form-item label="调度周期" prop="period">
                <ac-checkbox
                  v-model="formData.period"
                  options="1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30"
                />
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="12">
              <el-form-item label="业务类型" prop="businessType">
                <ac-radio
                  v-model="formData.businessType"
                  options="脚本,采集任务"
                />
              </el-form-item>
            </el-col>
            <el-col :span="12" v-if="formData.businessType === '脚本'">
              <el-form-item label="脚本名称" prop="businessId">
                <ac-tree
                  v-model="formData.businessId"
                  data-url="/system/scriptGroovy/queryTree"
                  type-select="script"
                />
              </el-form-item>
            </el-col>
            <el-col :span="12" v-if="formData.businessType === '采集任务'">
              <el-form-item label="采集任务" prop="businessId">
                <ac-remote-select
                  v-model="formData.businessId"
                  data-url="/system/collectTask/queryPage"
                  :option="{id: formData.businessId, name: formData.businessName}"
                />
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="12">
              <el-form-item label="状态" prop="status">
                <ac-radio
                  v-model="formData.status"
                  options="正常,暂停"
                ></ac-radio>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="参数" prop="params">
                <el-input v-model="formData.params" auto-complete="off"></el-input>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="24">
              <el-form-item label="备注" prop="remark">
                <el-input v-model="formData.remark" auto-complete="off" type="textarea" :rows="5"></el-input>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row v-if="!dialogEdit">
            <el-col :span="24">
              <el-form-item label="创建时间" prop="createTime">
                <ac-datetime v-model="formData.createTime" />
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
        <template #footer>
          <el-button 
            v-if="dialogEdit"
            size="default"
            type="info" 
            @click="dialogVisible=false"
          >取消</el-button>
          <el-button 
            v-if="dialogEdit"
            size="default"
            type="primary"
            @click="submitForm"
            :loading="editLoading"
          >提交</el-button>
          <el-button 
            v-if="!dialogEdit"
            size="default"
            type="info"
            @click="dialogVisible=false"
          >关闭</el-button>
        </template>
      </el-dialog>
    </div>

    <el-dialog
      v-model="fileVisible"
      width="500px"
      title="导入"
      :append-to-body="true"
      :close-on-click-modal="false"
      destroy-on-close
      draggable
    >
      <el-upload
        action=""
        :http-request="handleImport"
        :show-file-list=false
        accept=".dat"
      >
        <el-button :loading="fileLoading" type="primary">数据导入</el-button>
        <template #tip><div class="el-upload__tip">只能上传.dat文件</div></template>
      </el-upload>
      <template #footer>
        <div class="dialog-footer">
          <el-button
            size="default"
            @click="fileVisible=false"
            type="info"
          >取消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, nextTick } from 'vue'
import { ElMessage, ElMessageBox } from "element-plus";
import api from '@/http/api'

const filters = ref({
  type: '',
  businessId: ''
});
const filterFields = ref([
  {prop: "businessType", label: "业务类型", type: 'select', options: "脚本,采集任务"},
  {prop: "businessName", label: "业务名称"},
  {prop: "type", label: "类型", type: 'select', options: "每天,每周,每月,自定义"}
]);
const columns = ref([
  {prop: "businessName", label: "业务名称", minWidth: 120, click: true},
  {prop: "businessType", label: "业务类型", width: 120},
  {prop: "type", label: "调度类型", width: 100, type: 'buttons', options: "每天,每周,每月,自定义"},
  {prop: "time", label: "调度时间", width: 100},
  {prop: "period", label: "调度周期", minWidth: 120},
  {prop: "params", label: "参数", minWidth: 120},
  {prop: "expression", label: "表达式", minWidth: 140},
  {prop: "status", label: "状态", width: 80, type: 'select', options: "正常,暂停"},
  {prop: "remark", label: "备注", minWidth: 100},
  {prop: "updateTime", label: "更新时间", width: 160, type: "datetime"}
]);
const defaultSort = ref({prop: 'status', order: 'ascending'})

const dialogTitle = ref('')
const dialogVisible = ref(false)
const dialogEdit = ref(true)
const editLoading = ref(false)
const rules = ref({
  type: [{required: true, message: '请选择调度类型', trigger: ['change', 'blur']}],
  period: [{required: true, message: '请选择调度周期', trigger: ['change', 'blur']}],
  time: [{required: true, message: '请选择调度时间', trigger: ['change', 'blur']}],
  businessType: [{required: true, message: '请选择业务类型', trigger: ['change', 'blur']}],
  businessId: [{required: true, message: '请选择业务名称', trigger: ['change', 'blur']}],
  expression: [{required: true, message: '请输入表达式', trigger: ['change', 'blur']}],
  status: [{required: true, message: '请输入状态', trigger: 'change'}]
})
const formData = ref({})
const dataTable = ref({})
const dataForm = ref()
const fileVisible = ref(false);
const fileLoading = ref(false);

const handleImport = (file) => {
  api.uploadFile('/system/schedule/importData', {'file': file.file}).then((res) => {
    ElMessage.success(res.message);
    fileVisible.value = false;
    dataTable.value.findPage();
  });
};

const handleCellOperator = (property, value, row) => {
  formData.value = Object.assign({}, row);
  dialogEdit.value = false;
  dialogTitle.value = "查看";
  dialogVisible.value = true;

  nextTick(() => {
    dataForm.value && dataForm.value.clearValidate();
  });
};

const handleTableOperator = (button, row) => {
  if (button.buttonType === 'edit') {
    formData.value = Object.assign({}, row, {button: button});
    dialogVisible.value = true;
    dialogEdit.value = true;
    dialogTitle.value = button.name;
  } else if (button.buttonType === 'exportData') {
    const data = row.map(item => item.id);
    api.downloadFile('/system/schedule/exportData', {ids: data}).then(res => api.saveFileLocal(res));
  } else if (button.buttonType === 'importData') {
    fileVisible.value = true;
  } else {
    formData.value = {
      businessType: '脚本',
      type: '每天',
      time: '00:00:00',
      status: '正常',
      button: button
    };
    dialogVisible.value = true;
    dialogEdit.value = true;
    dialogTitle.value = button.name;
  }

  nextTick(() => {
    dataForm.value && dataForm.value.clearValidate();
  });
};

const submitForm = () => {
  dataForm.value && dataForm.value.validate((valid) => {
    if (valid) {
      ElMessageBox.confirm('请确认是否提交？', '提示', {type: 'info'}).then(() => {
        editLoading.value = true;
        api.post(formData.value.button.dataDestUrl, formData.value).then(res => {
          ElMessage.success(res.message);
          dialogVisible.value = false;
          dataTable.value.findPage();
          editLoading.value = false;
        }).catch(() => {
          editLoading.value = false;
        })
      }).catch(()=>{});
    } else {
      ElMessage.error('数据录入不正确，请重新检查！');
    }
  });
};
</script>

<style scoped lang="scss">
.edit-dialog :deep(.el-checkbox) {
  margin-right: 20px;
  .el-checkbox__label {
    min-width: 20px;
  }
}
</style>